package com.fzu.normalservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fzu.commonutil.entity.HousekeeperServiceType;
import com.fzu.commonutil.entity.ServiceType;
import com.fzu.commonutil.mapper.HousekeeperServiceTypeMapper;
import com.fzu.commonutil.mapper.ServiceTypeMapper;
import com.fzu.normalservice.service.HousekeeperServiceTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zyq
 * @since 2023-03-26
 */
@Service
@RequiredArgsConstructor
public class HousekeeperServiceTypeServiceImpl extends ServiceImpl<HousekeeperServiceTypeMapper, HousekeeperServiceType> implements HousekeeperServiceTypeService {

    private final ServiceTypeMapper serviceTypeMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void operate(Integer housekeeperId, List<Integer> typeIdList) {
        LambdaQueryWrapper<HousekeeperServiceType> wrapper =  new LambdaQueryWrapper<>();
        wrapper.eq(HousekeeperServiceType::getHousekeeperId, housekeeperId);
        List<HousekeeperServiceType> oldList = super.list(wrapper);
        // 删除旧的关联关系
        if (!CollectionUtils.isEmpty(oldList)) {
            Set<Integer> ids = oldList.stream().map(HousekeeperServiceType::getId).collect(Collectors.toSet());
            super.removeByIds(ids);
        }
        // 保存新的关联关系
        List<HousekeeperServiceType> entityList = new ArrayList<>();
        for (Integer typeId : typeIdList) {
            entityList.add(new HousekeeperServiceType().setTypeId(typeId).setHousekeeperId(housekeeperId));
        }
        super.saveBatch(entityList);
    }

    @Override
    public List<ServiceType> listByHousekeeperId(Integer housekeeperId) {
        LambdaQueryWrapper<HousekeeperServiceType> wrapper =  new LambdaQueryWrapper<>();
        wrapper.eq(HousekeeperServiceType::getHousekeeperId, housekeeperId);
        List<HousekeeperServiceType> list = super.list(wrapper);
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        Set<Integer> typeIds = list.stream().map(HousekeeperServiceType::getTypeId).collect(Collectors.toSet());
        return serviceTypeMapper.selectBatchIds(typeIds);
    }
}
